<?php

require 'phpQuery.php';
require 'QueryList.php';

use  QL\QueryList;

//interface.php
//接口文件
function vuespa_create_api()
{
    register_rest_route('pf/v1', '/get_option/', array( // 完整命名空间为：/wp-json/pf/v1/
        'methods' => 'POST',
        'callback' => 'get_option_by_RestAPI',
    ));
    register_rest_route('pf/v1', '/update_option/', array( // 完整命名空间为：/wp-json/pf/v1/
        'methods' => 'POST',
        'callback' => 'update_option_by_RestAPI',
        'permission_callback' => function () {
            return current_user_can('manage_options'); // 只有管理员才有权限修改
        },
    ));
    register_rest_route('pf/v1','/menus/',array(
        'methods' => 'POST',
        'callback' => 'addMenu',
        'permission_callback' => function () {
            return current_user_can('manage_options'); // 只有管理员才有权限修改
        },
    ));
}
add_action('rest_api_init', 'vuespa_create_api');


//添加网站
function addMenu($data){
    // print_r('<pre>');
    // print_r($data);
    // print_r($data['siteName']);
    // print_r($data['siteUrl']);
}


//添加网站接口
add_action('wp_ajax_addMenu_list','addMenu_list');
add_action('wp_ajax_nopriv_addMenu_list','addMenu_list');
function addMenu_list(){
    $post_json = json_decode(str_replace("\\","",$_POST['data']));
    $postData = array(
        'post_author'   => 1,
        'post_title'    => $post_json->siteName,
        'post_type'     => 'menu',
        'post_status'   => 'publish'
    );
    $result = wp_insert_post($postData);
    update_post_meta($result,'_menu', $post_json->siteUrl);
    $datas = array(
        'code' => 1,
        'rid' => $result,
        'msg'  => '成功'
    );
    wp_send_json($datas);
}

//获取网站列表
add_action('wp_ajax_get_artlists','get_artlists');
add_action('wp_ajax_nopriv_get_artlists','get_artlists');
function get_artlists(){
    $arg = get_posts(array(
        'post_type' => 'menu',
        'numberposts' => 100
    ));
    $datas = array(
        'code' => 1,
        'msg'  => '成功',
        'data' => $arg
    );
    wp_send_json($datas);
}

//获取网站参数
add_action('wp_ajax_get_art_list','get_art_list');
add_action('wp_ajax_nopriv_get_art_list','get_art_list');
function get_art_list(){
    $post_id = $_POST['id'];
    $redatas = array(
        'code' => 1,
        'msg'  => '成功',
        'data' => array(
            'url'   => get_post_meta($post_id,'_menu',true),
            'title' => get_post_meta($post_id,'_title',true),
            'time' => get_post_meta($post_id,'_time',true),
            'content' => get_post_meta($post_id,'_content',true),
            'description' => get_post_meta($post_id,'_description',true),
            'Infotitle' => get_post_meta($post_id,'_Infotitle',true),
        )
    );
    wp_send_json($redatas);
}

//提交网站参数接口
add_action('wp_ajax_get_artlistses','get_artlistses');
add_action('wp_ajax_nopriv_get_artlistses','get_artlistses');
function get_artlistses(){
    $post_id = $_POST['id'];
    $post_data = json_decode(str_replace('\\','',$_POST['data']));
    update_post_meta($post_id,'_menu', $post_data->url);
    update_post_meta($post_id,'_title', $post_data->title);
    update_post_meta($post_id,'_time', $post_data->time);
    update_post_meta($post_id,'_content', $post_data->content);
    update_post_meta($post_id,'_description', $post_data->description);
    update_post_meta($post_id,'_Infotitle', $post_data->Infotitle);
    $datas = array(
        'code' => 1,
        'msg'  => '成功'
    );
    wp_send_json($datas);
}



//采集接口
add_action('wp_ajax_caijiFun','caijiFun');
add_action('wp_ajax_nopriv_caijiFun','caijiFun');
function caijiFun(){
    // $datas = json_decode($_POST['data'],true);
    $post_data = json_decode(str_replace('\\','',$_POST['data']));
    $url = $post_data->url;
    $title = $post_data->title;
    //内容页标签配置
    $Infotitle = $post_data->Infotitle;
    $time = $post_data->time;
    $description = $post_data->description;
    $content = $post_data->content;
     //开始采集
     $rules = array(
         'title'=>array($title,'text','p'),    
         'url'  => array($title,'href')              
     );
     $hj = QueryList::Query($url,$rules);
     $caijiData = $hj->data;
     $cjData = array();
     foreach($caijiData as $key=>$value){
        //开始采集
        $rules = array(
            'title'=>array($Infotitle,'text'),    
            'content'  => array($content,'html')              
        );
        $hj1 = QueryList::Query($value['url'],$rules);
        $q = $hj1->data;
        array_push($cjData,$q[0]);
     }
     wp_send_json($cjData);
}


//获取所有栏目
add_action('wp_ajax_get_cate_by_RestAPI','get_cate_by_RestAPI');
add_action('wp_ajax_nopriv_get_cate_by_RestAPI','get_cate_by_RestAPI');
function get_cate_by_RestAPI(){
    $cate = get_terms(array(
        'taxonomy' => 'category',
        'hide_empty' => false,
    ));
    wp_send_json($cate);
}

//将选择的分类存到数据库
add_action('wp_ajax_add_cate_by_RestAPI','add_cate_by_RestAPI');
add_action('wp_ajax_nopriv_add_cate_by_RestAPI','add_cate_by_RestAPI');
function add_cate_by_RestAPI(){
    $cateIdList = json_decode(str_replace('\\','',$_POST['cateData']));
    $cate_id = $_POST['cate_id'];

    //找出所有栏目
    $cate = get_terms(array(
        'taxonomy' => 'category',
        'hide_empty' => false,
    ));

    //过滤出选择的栏目名称
    $arrID = array();
    foreach($cate as $key=>$value){
        if(in_array($value->term_id,$cateIdList)){
            array_push($arrID,$value);
        }
    }
    //找出先前存的栏目并删除
    $arrLists = get_posts(array(
        'post_type'  => 'menu_type',
        'meta_query' => array(
            array(
                'key'    => '_gl_menu',
                'value'  => $cate_id,
            )
        )
    ));
    foreach($arrLists as $key=>$v){
        wp_delete_post($v->ID);
    }
    //存入新选的栏目
    foreach($arrID as $key=>$i){
        $postes = array(
            'post_author'  => 1,
            'post_title'    => $i->name,
            'post_status' => 'publish',
            'post_type' => 'menu_type',
        );
        $result = wp_insert_post($postes);
        update_post_meta($result,'_gl_menu',$cate_id);
    }
    //返回数据
    wp_send_json(array('status'=>1,'msg'=>'success'));
}
//将即使任务数据填入到数据库
// add_action('wp_ajax_set_task_by_RestAPI','set_task_by_RestAPI');
// add_action('wp_ajax_nopriv_set_task_by_RestAPI','set_task_by_RestAPI');
// function set_task_by_RestAPI(){
// }
//把文章随机分配到栏目
add_action('wp_ajax_set_in_cate_by_RestAPI','set_in_cate_by_RestAPI');
add_action('wp_ajax_nopriv_set_in_cate_by_RestAPI','set_in_cate_by_RestAPI');
function set_in_cate_by_RestAPI(){
    $cateIdList = json_decode(str_replace('\\','',$_POST['cateIdList']));
    // str_replace(array('\r\n','\r','\n','\\'),'',$_FILES['html']);
    $arr = str_replace(array('\\','\n','\r'),'',strip_tags($_POST['cateData'],"<p><h><h1><h2><h3>"));
    $newArr = json_decode($arr,true);
    foreach ($newArr as $val){
        $links = $cateIdList[mt_rand(0, count($cateIdList)-1)];
        $strcontent = get_post(array( 'post_title' => $val['title']));
        if(is_null($strcontent)){
            $post_arr = array(
                'post_author'  => 1,
                'post_title' => $val['title'],
                'post_content' => $val['content'],
                'post_status' => 'publish',
                'post_type' => 'post',
                'post_category' => array($links),
            );
            $result = wp_insert_post($post_arr);
        }
    }
    wp_send_json(array('code'=>1,'msg'=>'success'));
}



//读取Option
//支持数组类数据请求
function get_option_by_RestAPI($data)
{
    // 将输入数据转换成数组类型 
    $dataArray = json_decode($data->get_body(), true);
    $return = array();
    // 遍历数组，检查每个元素是否为对象
    foreach ($dataArray as $option_name => $value) {
        // 初始化当前选项的值数组
        $option_value = array();
        // 如果当前元素是一个非空数组，则遍历其中的每个字段
        if (is_array($value) && !empty($value)) {
            foreach ($value as $field_name => $field_value) {
                // 获取指定选项的值，如果不存在，则使用空字符串代替
                $option_value[$field_name] = get_option($field_name, '');
            }
            // 将当前选项及其值添加到返回数组中
            $return[$option_name] = $option_value;
        } else {
            // 如果当前元素非数组或数组为空，获取指定选项的值
            $return[$option_name] = get_option($option_name, '');
        }
    }
    return $return; // 返回所有选项的键值对
}


//保存Option
function update_option_by_RestAPI($data)
{
    //判断是否是管理员
    if (current_user_can('manage_options')) {
        //转为JSON对象 - 重点，这里没有true，是转为对象
        $dataArray = json_decode($data->get_body());
        //存储结果
        $result = new stdClass();
        //循环保存选项
        foreach ($dataArray as $option_name => $value) {
            //判断，是否为对象
            if (is_object($value)) {
                //是非空数组，循环保存值
                foreach ($value as $arr => $data) {
                    //更新值    
                    update_option($arr, $data);
                }
            } else {
                //不是对象，则表示只有一个选项需要保存。
                update_option($option_name, $value);
            }
            $result->$option_name = $value;
        }
        //返回成功信息
        return new WP_REST_Response(array(
            'success' => true,
            'message' => "已保存！"
        ), 200);
    } else {
        //返回失败信息
        return new WP_Error('save_error', '保存失败！', array('status' => 500));
    }
}